package com.sinogrand.elevator.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.zIndex
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.foundation.text.BasicTextField
import kotlinx.coroutines.delay

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProjectListScreen(
    projects: List<ProjectItem>,
    onRefresh: () -> Unit,
    onLoadMore: () -> Unit,
    onProjectClick: (ProjectItem) -> Unit,
    onSearch: (String) -> Unit = {}, // 新增搜索回调
    isLoadingMore: Boolean = false,
    canLoadMore: Boolean = true,
    isSearching: Boolean = false, // 新增搜索加载状态
    paddingValues: PaddingValues = PaddingValues()
) {
    var searchQuery by rememberSaveable { mutableStateOf("") }
    var searchText by rememberSaveable { mutableStateOf("") } // 用于输入框显示
    val listState = rememberSaveable(saver = LazyListState.Saver) {
        LazyListState()
    }
    val pullRefreshState = rememberPullToRefreshState()
    
    // 使用传入的项目列表，不再进行本地过滤
    val filteredProjects = projects
    
    // 下拉刷新
    LaunchedEffect(pullRefreshState.isRefreshing) {
        if (pullRefreshState.isRefreshing) {
            onRefresh()
            delay(1000) // 模拟网络请求
            pullRefreshState.endRefresh()
        }
    }
    
    // 上拉加载更多
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
            .collect { lastVisibleIndex ->
                if (lastVisibleIndex != null && 
                    lastVisibleIndex >= filteredProjects.size - 1 && 
                    canLoadMore && 
                    !isLoadingMore &&
                    searchQuery.isBlank() &&
                    filteredProjects.isNotEmpty()) { // 确保列表不为空
                    onLoadMore()
                }
            }
    }
    
    // 监听滑动状态，滑动时隐藏键盘
    val keyboardController = LocalSoftwareKeyboardController.current
    LaunchedEffect(listState) {
        snapshotFlow { listState.isScrollInProgress }
            .collect { isScrolling ->
                if (isScrolling) {
                    keyboardController?.hide()
                }
            }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(paddingValues)
            .background(
                Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFFF8FAFC),
                        Color(0xFFF1F5F9)
                    )
                )
            )
    ) {
        // 固定搜索栏
        SearchBar(
            query = searchText,
            onQueryChange = { searchText = it },
            onSearch = { 
                searchQuery = searchText
                onSearch(searchText)
            },
            onClear = {
                searchText = ""
                searchQuery = ""
                onSearch("")
            },
            placeholder = "请输入内容",
            isSearching = isSearching,
            modifier = Modifier
                .padding(16.dp)
                .height(48.dp)
        )
        
        // 列表区域 - 使用Box包装以支持下拉刷新
        Box(
            modifier = Modifier.weight(1f)
        ) {
            LazyColumn(
                state = listState,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 16.dp)
                    .nestedScroll(pullRefreshState.nestedScrollConnection),
                verticalArrangement = Arrangement.spacedBy(12.dp),
                contentPadding = PaddingValues(
                    top = 8.dp,
                    bottom = 8.dp
                )
            ) {
            
                // 项目列表
                if (filteredProjects.isEmpty()) {
                    item {
                        if (searchQuery.isBlank()) {
                            EmptyState(
                                title = "暂无数据",
                                description = "当前没有项目数据，请稍后再试"
                            )
                        } else {
                            EmptyState(
                                title = "没有找到项目",
                                description = "没有找到包含\"$searchQuery\"的项目，请尝试其他关键词"
                            )
                        }
                    }
                } else {
                    items(filteredProjects) { project ->
                        ProjectItemCard(
                            project = project,
                            onClick = { onProjectClick(project) }
                        )
                    }
                }
                
                // 加载更多指示器
                if (isLoadingMore && searchQuery.isBlank()) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(20.dp),
                                    strokeWidth = 2.dp,
                                    color = Color(0xFF3B82F6)
                                )
                                Spacer(modifier = Modifier.width(6.dp))
                                Text(
                                    text = "加载中...",
                                    fontSize = 14.sp,
                                    color = Color(0xFF6B7280)
                                )
                            }
                        }
                    }
                }
                
                // 没有更多数据提示
                if (!canLoadMore && filteredProjects.isNotEmpty() && searchQuery.isBlank()) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 16.dp, vertical = 4.dp), // 进一步减少垂直padding到4dp
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "没有更多数据了",
                                fontSize = 14.sp,
                                color = Color(0xFF6B7280)
                            )
                        }
                    }
                }
            }
            
            // 下拉刷新容器 - 只在需要时显示
            if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
                PullToRefreshContainer(
                    state = pullRefreshState,
                    modifier = Modifier
                        .align(Alignment.TopCenter)
                        .zIndex(1f) // 确保在列表内容之上
                )
            }
        }
    }
}

@Composable
fun SearchBar(
    query: String,
    onQueryChange: (String) -> Unit,
    onSearch: () -> Unit,
    onClear: () -> Unit = {},
    placeholder: String = "搜索",
    isSearching: Boolean = false,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 10.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.Default.Search,
                contentDescription = null,
                tint = Color(0xFF6B7280),
                modifier = Modifier.size(24.dp) // 进一步增大搜索图标
            )
            
            Spacer(modifier = Modifier.width(6.dp))
            
            val keyboardController = LocalSoftwareKeyboardController.current
            
            BasicTextField(
                value = query,
                onValueChange = onQueryChange,
                modifier = Modifier
                    .weight(1f)
                    .height(48.dp),
                textStyle = androidx.compose.ui.text.TextStyle(
                    fontSize = 14.sp,
                    color = Color(0xFF1F2937)
                ),
                decorationBox = { innerTextField ->
                    Box(
                        modifier = Modifier.fillMaxWidth(),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        if (query.isEmpty()) {
                            Text(
                                text = placeholder,
                                color = Color(0xFF9CA3AF),
                                fontSize = 14.sp,
                                lineHeight = 10.sp
                            )
                        }
                        innerTextField()
                    }
                },
                singleLine = true,
                keyboardOptions = KeyboardOptions(
                    imeAction = ImeAction.Search
                ),
                keyboardActions = KeyboardActions(
                    onSearch = {
                        onSearch()
                        keyboardController?.hide()
                    }
                )
            )
            
            if (isSearching) {
                Box(
                    modifier = Modifier.size(28.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        strokeWidth = 2.dp,
                        color = Color(0xFF3B82F6)
                    )
                }
            } else if (query.isNotEmpty()) {
                IconButton(
                    onClick = onClear, // 使用onClear回调
                    modifier = Modifier.size(28.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Clear,
                        contentDescription = "清除搜索",
                        tint = Color(0xFF6B7280),
                        modifier = Modifier.size(14.dp)
                    )
                }
            }
        }
    }
}
